﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace EventScavenger
{
    public partial class ReaperSetupHelper : Form
    {
        public ReaperSetupHelper()
        {
            InitializeComponent();
        }

        private Collector selectedCollector = new Collector();
        public Collector SelectedCollector
        {
            get { return selectedCollector; }
            set { selectedCollector = value; }
        }

        #region Form events
        private void ReaperSetupHelper_Load(object sender, EventArgs e)
        {
            txtReaper.Text = selectedCollector.ReaperName;
            txtName.Text = selectedCollector.Name;
            txtServiceName.Text = selectedCollector.ServiceName;
            txtServicePath.Text = selectedCollector.ServicePath;
            GenerateHelpText();
        } 
        #endregion

        #region Button events
        private void cmdTest_Click(object sender, EventArgs e)
        {
            GenerateHelpText();
            if (TestServiceExistance(txtReaper.Text, txtServiceName.Text, false))
                MessageBox.Show("Success!\r\nService can be accessed", "Service", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void cmdOK_Click(object sender, EventArgs e)
        {
            if (txtServiceName.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must specify a service name!", "Service name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtServiceName.Focus();
            }
            else if (txtServicePath.Text.Trim().Length == 0)
            {
                MessageBox.Show("You must specify a service path!", "Service name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtServicePath.Focus();
            }  
            else
            {
                selectedCollector.ReaperName = txtReaper.Text;
                selectedCollector.ServiceName = txtServiceName.Text;
                selectedCollector.ServicePath = txtServicePath.Text;
                selectedCollector.Name = txtName.Text;
                DialogResult = DialogResult.OK;
                Close();
            }
        } 
        private void cmdBrowseServicePath_Click(object sender, EventArgs e)
        {
            if (txtServicePath.Text.Length > 0)
            {
                openFileDialogEventReaper.FileName = txtServicePath.Text;
                openFileDialogEventReaper.InitialDirectory = System.IO.Path.GetDirectoryName(txtServicePath.Text);
            }
            if (openFileDialogEventReaper.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtServicePath.Text = openFileDialogEventReaper.FileName;
            }
        }
        private void cmdConfigFile_Click(object sender, EventArgs e)
        {
            try
            {
                string configFilePath = "";
                if (System.Net.Dns.GetHostName().StartsWith(txtReaper.Text, StringComparison.CurrentCultureIgnoreCase))
                    configFilePath = txtServicePath.Text + ".config";
                else
                {
                    configFilePath = "\\\\" + txtReaper.Text + "\\" + txtServicePath.Text + ".config";
                    configFilePath = configFilePath.Replace(":", "$");
                }
                if (System.IO.File.Exists(configFilePath))
                {
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo = new System.Diagnostics.ProcessStartInfo("notepad.exe");
                    p.StartInfo.Arguments = configFilePath;
                    p.Start();
                }                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region Text box events
        private void txtServiceName_TextChanged(object sender, EventArgs e)
        {
            timerServiceRegistrationHelpUpdate.Enabled = false;
            timerServiceRegistrationHelpUpdate.Enabled = true;
        } 
        #endregion

        #region Timer events
        private void timerServiceRegistrationHelpUpdate_Tick(object sender, EventArgs e)
        {
            try
            {
                timerServiceRegistrationHelpUpdate.Enabled = false;
                GenerateHelpText();
                string configFilePath = "";
                if (System.Net.Dns.GetHostName().StartsWith(txtReaper.Text, StringComparison.CurrentCultureIgnoreCase))
                    configFilePath = txtServicePath.Text + ".config";
                else
                {
                    configFilePath = "\\\\" + txtReaper.Text + "\\" + txtServicePath.Text + ".config";
                    configFilePath = configFilePath.Replace(":", "$");
                }
                cmdConfigFile.Enabled = System.IO.File.Exists(configFilePath);
            }
            catch (Exception ex)
            {
                txtServiceRegistration.Text = ex.Message;
            }        }
        #endregion

        #region Private methods
        private void GenerateHelpText()
        {
            string path = "";
            if (System.IO.File.Exists(txtServicePath.Text))
                path=  System.IO.Path.GetDirectoryName(txtServicePath.Text);
            string helpText = "The following is simply to help you set up an instance of Event Reaper Service.\r\n";
            helpText += "1. Log on to the server '" + txtReaper.Text + "'\r\n";
            helpText += string.Format("2. Copy EventReaper.exe and EventReaper.exe.config to a \"{0}\"\r\n", path);
            helpText += "   Optionally you can reuse an existing copy if it already points to the same sql server and database\r\n";
            helpText += "3. Open an Administrative command window (cmd.exe)\r\n";
            helpText += string.Format("4. Run \"{0}\" -install \"{1}\" \"Event Reaper - {1}\"\r\n", txtServicePath.Text, txtName.Text);
            helpText += string.Format("5. (optionally) Edit EventReaper.exe.config and set collector name e.g:\r\n" +
                        "\t<setting name=\"CollectorName\" serializeAs=\"String\">\r\n" +
                        "\t\t<value>{0}</value>\r\n" +
                        "\t</setting>\r\n", txtName.Text);
            helpText += "6. Edit connection settings in config file\r\n";
            helpText += "7. Remember to restart service if config file has been changed\r\n";
            helpText += string.Format("\r\nX. To uninstall run: EventReaper.exe -uninstall \"{0}\"\r\n", txtName.Text);

            txtServiceRegistration.Text = helpText;
        }
        private bool TestServiceExistance(string serverName, string serviceName, bool allowContinue = true)
        {
            bool ignoreError = false;
            try
            {
                System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceName, serverName);
                string s = sc.ServiceName;
                ignoreError = true;
            }
            catch (Exception ex)
            {
                if (allowContinue && MessageBox.Show("The specified service does not exist yet or cannot be accessed!\r\nContinue anyway?\r\nDetails:\r\n  " +
                        ex.Message.Replace("\r\n", "  \r\n"), "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.Yes)
                {
                    ignoreError = true;
                }
                else
                {
                    MessageBox.Show("The specified service does not exist yet or cannot be accessed!\r\nDetails:\r\n  " +
                        ex.Message.Replace("\r\n", "  \r\n"), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            return ignoreError;
        } 
        #endregion

    }
}
